package bb.lanxing.model.database;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.litepal.LitePal;

import android.bluetooth.BluetoothDevice;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.TextUtils;
import android.util.Log;

import bb.lanxing.App;
import bb.lanxing.devices.utils.XZDeviceHelper;
import bb.lanxing.lib.devices.api.SmartDevice;
import bb.lanxing.lib.devices.base.DeviceContext;
import gov.nist.core.Separators;


public class Device extends LitePalTableBase implements Parcelable, SmartDevice {
    final private static String TAG = "Device";
    public static final Parcelable.Creator<Device> CREATOR = new Parcelable.Creator<Device>() {

        @Override
        public Device createFromParcel(Parcel parcel) {
            return new Device(parcel);
        }

        @Override
        public Device[] newArray(int i) {
            return new Device[i];
        }
    };
    private String address;
    private int available;
    private String bikeId;
    private int capacity;
    private int deviceAutoPower;
    private int deviceColor;
    private String deviceFwDisplayVersion;
    private String deviceFwName;
    private int deviceFwVersion;
    private int deviceMode;
    private int deviceNumber;
    private int deviceTotalCranks;
    private int deviceTotalWheels;
    private String deviceUUID;
    private int deviceWidthLight;
    private int flags;
    private String initialPasscode;
    private boolean isInfoUpload;
    private String localFwFileName;
    private String localFwFilePath;
    private String name;
    private int protocol;
    private int rssi;

    private byte[] scanRecord;
    private String serverFwDate;
    private String serverFwDesc;
    private String serverFwDisplayVersion;
    private String serverFwName;
    private String serverFwUpdateLog;
    private String serverFwUrl;
    private int serverFwVersion;
    private String simNumber;
    private int type;
    private long userId;


    public static int[] getSecondGenerationDevice() {
        return new int[]{SmartDevice.TYPE_XOSS_NAV};
    }

    @Override
    public int describeContents() {
        return 0;
    }

    public Device() {
    }

    public Device(Parcel parcel) {
        readFromParcel(parcel);
    }

    @Override
    public void readFromParcel(Parcel parcel) {
        this.name = parcel.readString();
        this.address = parcel.readString();
        this.type = parcel.readInt();
        this.rssi = parcel.readInt();
        this.userId = parcel.readLong();
        this.deviceUUID = parcel.readString();
        this.deviceNumber = parcel.readInt();
        this.simNumber = parcel.readString();
        this.initialPasscode = parcel.readString();
        this.bikeId = parcel.readString();
        this.capacity = parcel.readInt();
        this.available = parcel.readInt();
        this.deviceColor = parcel.readInt();
        this.deviceMode = parcel.readInt();
        this.deviceAutoPower = parcel.readInt();
        this.deviceWidthLight = parcel.readInt();
        this.deviceTotalWheels = parcel.readInt();
        this.deviceTotalCranks = parcel.readInt();
        this.deviceFwVersion = parcel.readInt();
        this.deviceFwDisplayVersion = parcel.readString();
        this.serverFwVersion = parcel.readInt();
        this.serverFwDisplayVersion = parcel.readString();
        this.serverFwName = parcel.readString();
        this.serverFwDate = parcel.readString();
        this.serverFwDesc = parcel.readString();
        this.serverFwUpdateLog = parcel.readString();
        this.serverFwUrl = parcel.readString();
        this.localFwFileName = parcel.readString();
        this.localFwFilePath = parcel.readString();
        this.isInfoUpload = parcel.readByte() != 0;
        this.deviceFwName = parcel.readString();
        this.flags = parcel.readInt();
//        Log.d(TAG, "readFromParcel flags=" + this.flags);
        this.protocol = parcel.readInt();
    }

//    public static void deleteAll(Class<Device> device, String where, String param1, String param2) {
//
//        LitePal.deleteAll(device, where, param1, param2);
//
//    }

    public static List<Device> getByUserId(long userId) {
        //TODO:sun, input parameter not used
//        String userId = String.valueOf(App.getContext().getUserId());
        Log.d(TAG, "getByUserId userId=" + userId);
        List<Device> l = LitePal.where("userId=? or userId=0", String.valueOf(userId)).find(Device.class);
        return l;


//        return Select.from(Device.class).where(" user_id = ? or user_id = 0 ", new String[]{String.valueOf(j)}).list();

    }

    public static boolean needAutoConnect(BluetoothDevice bluetoothDevice, long userId) {

        if (bluetoothDevice == null) {
            return false;
        }

        String strUserId = String.valueOf(userId);//TODO:sun
        String address = bluetoothDevice.getAddress();

        List<Device> l = LitePal.where("address=? and (userId=? or userId=0)", address, strUserId).find(Device.class);
        if (l == null || l.size() == 0) {
            return false;
        }

        return true;
//        return bluetoothDevice != null && Select.from(Device.class).where(" (user_id = ? or user_id = 0) and address = '?' ", new String[]{String.valueOf(j), bluetoothDevice.getAddress()}).count() > 0;
    }

    public static Device getConnectedDevice(int type) {

        String userId = String.valueOf(App.getContext().getUserId());
        String devType = String.valueOf(type);
        Log.d(TAG, "getConnectedDevice type=" + type);
        List<Device> list = LitePal.where(" type = ? and userId = ?", devType, userId).find(Device.class);

//        List<Device> list = Select.from(Device.class).where(" type = ? and user_id = ?", new String[]{String.valueOf(i), String.valueOf(App.getContext().getUserId())}).list();
        if (!list.isEmpty()) {
            for (Device device : list) {
                if (XZDeviceHelper.isConnected(device.getAddress())) {
                    return device;
                }
            }
            return null;
        }
        return null;
    }

    public static Device getByAddress(String address) {
        if (TextUtils.isEmpty(address)) {
            return null;
        }
        Log.d(TAG, "getByAddress address=" + address);
        Device d = LitePal.where("address=?", address).findFirst(Device.class);
        return d;
    }

    public static Device getByAddress(String address, long userId) {
        if (TextUtils.isEmpty(address)) {
            return null;
        }
        Log.d(TAG, "getByAddress address=" + address + ", userId=" + userId);
        Device d = LitePal.where("address=? and userId=?", address, String.valueOf(userId)).findFirst(Device.class);
        return d;
    }

    public static Device getByType(int type) {

        String userId = String.valueOf(App.getContext().getUserId());
        String devType = String.valueOf(type);
        Log.d(TAG, "getByType type=" + type);
        Device d = LitePal.where("type=? and userId=?", devType, userId).findFirst(Device.class);
        return d;
//        List list = Select.from(Device.class).where(" type = ? and user_id = ?", new String[]{String.valueOf(i), String.valueOf(App.getContext().getUserId())}).list();
//        if (list.size() > 0) {
//            return (Device) list.get(0);
//        }
//        return null;
    }

    public static List<Device> getDevicesByType(int type) {
        String userId = String.valueOf(App.getContext().getUserId());
        String devType = String.valueOf(type);

        List<Device> l = LitePal.where("type=? and userId=?", devType, userId).find(Device.class);
        return l;
//        return Select.from(Device.class).where(" type = ? and user_id = ?", new String[]{String.valueOf(i), String.valueOf(App.getContext().getUserId())}).list();
    }

    public static List<Device> getAllDevices() {
        String userId = String.valueOf(App.getContext().getUserId());
        Log.d(TAG, "getAllDevices userId=" + userId);
        List<Device> l = LitePal.where("userId=?", userId).find(Device.class);
        return l;
//        return Select.from(Device.class).where("user_id = ?", new String[]{String.valueOf(App.getContext().getUserId())}).list();
    }

    public static synchronized Device storeDevice(Device device) {
        synchronized (Device.class) {
            if (device != null) {
                String address = device.getAddress();
                if (!TextUtils.isEmpty(address)) {
                    if (TextUtils.isDigitsOnly(address)) {
                        device.setProtocol(SmartDevice.PROTOCOL_ANT_PLUS);
                    } else {
                        device.setProtocol(SmartDevice.PROTOCOL_BLE);
                    }
                    Device byAddress = getByAddress(address);
                    if (byAddress != null) {
                        device.setId(byAddress.getId());
                    }
                    device.setUserId(App.getContext().getUserId());
                    device.save2();
                    return device;
                }
            }
            return device;
        }
    }

//    public static synchronized void saveDevice(Device device) {
//        synchronized (Device.class) {
//            if (device != null) {
//                String address = device.getAddress();
//                Log.d(TAG, "hulin-saveDevice: address=" + address);
//                if (!TextUtils.isEmpty(address)) {
//                    if (TextUtils.isDigitsOnly(address)) {
//                        device.setProtocol(SmartDevice.PROTOCOL_ANT_PLUS);
//                    } else {
//                        device.setProtocol(SmartDevice.PROTOCOL_BLE);
//                    }
//                    Device byAddress = getByAddress(address);
//                    if (byAddress != null) {
//                        device.setId(byAddress.getId());
//                    }
//                    device.setUserId(App.getContext().getUserId());
//                    Device existDevice = getByAddress(address);
//                    Log.d(TAG, "hulin-saveDevice: existDevice=" + existDevice);
//                    if (existDevice != null) {
//                        Log.d(TAG, "hulin-saveDevice: existDevice id=" + existDevice.getId() + ",rssi=" + existDevice.getRssi());
//                        ContentValues contentValues = new ContentValues();
//                        contentValues.put("rssi", device.getRssi());
//                        device.update(contentValues);
//
//                        Device existDevice2 = getByAddress(address);
//                        if (existDevice2 != null) {
//                            Log.d(TAG, "hulin-saveDevice: existDevice2 id=" + existDevice2.getId() + ",rssi=" + existDevice2.getRssi());
//                        } else {
//                            Log.d(TAG, "hulin-saveDevice: existDevice2 null");
//                        }
//                    } else {
//                        device.save2();
//                    }
//                }
//            }
//        }
//    }
//    @Override
//    public long save() {
//        return storeDevice(this).getId().longValue();
//    }

    private void save2() {
        Log.d("LitePal", "hulin-save2...");
        super.save();
    }

//    public static boolean isDeviceBound(int type) {
//        return getByType(type) != null;
//    }

    public static boolean isSecondGenerationDevice(int deviceType) {
        for (int i : getSecondGenerationDevice()) {
            if (i == deviceType) {
                return true;
            }
        }
        return false;
    }
    public static void deleteByAddress(String address) {
        LitePal.deleteAll(Device.class, "address=?", address);
    }
//    public static int[] getFirstGenerationDevice() {
//        return new int[]{17, 9, 27, 29, 26, 14};
//    }

    public static boolean hasBoundedDevices() {
        ArrayList<Device> arrayList = new ArrayList<>();
        for (Device device : getAllDevices()) {
            if (isThisTypeNeedAutoConnect(device.type)) {
                arrayList.add(device);
            }
        }
        return !arrayList.isEmpty();
    }

    public boolean equals(Object btDevice) {
        if (btDevice instanceof BluetoothDevice bluetoothDevice) {
            bluetoothDevice.getAddress();
            return this.address.equals(bluetoothDevice.getAddress());
        } else if (btDevice instanceof Device) {
            return this.address.equals(((Device) btDevice).getAddress());
        } else {
            return false;
        }
    }

    public String getDescription() {
        int protocol = getProtocol();
        if (protocol == PROTOCOL_BLE || protocol == 0) {
            switch (type) {
                case SmartDevice.TYPE_BICI -> {
                    return "基本概念启孜智能自行车";
                }
                case SmartDevice.TYPE_CADENCE -> {
                    return "标准蓝牙踏频器";
                }
                case SmartDevice.TYPE_HEARTRATE -> {
                    return "标准蓝牙心率带";
                }
                case SmartDevice.TYPE_SMARTWATCH -> {
                    return "手表";
                }
                case SmartDevice.TYPE_Q1 -> {
                    return "智能骑行辅助";
                }
                case SmartDevice.TYPE_HEARTRATE_BELT -> {
                    return "XOSS蓝牙心率臂带";
                }
                case SmartDevice.TYPE_SENSOR_HEART_RATE -> {
                    return "Vortex";
                }
                case SmartDevice.TYPE_HR_X2_PRO -> {
                    return "XOSS_X2_PRO蓝牙心率带";
                }
                default -> {
                    return "其它";
                }
            }

        } else if (protocol == PROTOCOL_ANT_PLUS) {
            switch (type) {
                case SmartDevice.TYPE_CADENCE -> {
                    return "ANT+踏频器";
                }
                case SmartDevice.TYPE_HEARTRATE -> {
                    return "ANT+心率带";
                }
                default -> {
                    return "其它";
                }
            }
        } else {
            return "";
        }
    }


    public boolean isInfoUpload() {
        return this.isInfoUpload;
    }

    public void setIsInfoUpload(boolean isInfoUpload) {
        this.isInfoUpload = isInfoUpload;
    }

    @Override
    public int getRssi() {
        return this.rssi;
    }

    @Override
    public void setRssi(int rssi) {
        this.rssi = rssi;
    }

    @Override
    public String getName() {
        return this.name;
    }

    @Override
    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String getAddress() {
        return this.address;
    }

    @Override
    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public int getType() {
        return this.type;
    }

    @Override
    public void setType(int type) {
        this.type = type;
    }

    public long getUserId() {
//        Log.d(TAG, "getUserId this.userId=" + this.userId);
        return this.userId;
    }

    public void setUserId(long userId) {
//        Log.d(TAG, "setUserId userId=" + userId);
        this.userId = userId;
    }

    public String getDeviceUUID() {
        return this.deviceUUID;
    }

    public void setDeviceUUID(String deviceUUID) {
        this.deviceUUID = deviceUUID;
    }

    public int getDeviceNumber() {
        return this.deviceNumber;
    }

    public void setDeviceNumber(int deviceNumber) {
        this.deviceNumber = deviceNumber;
    }

    public String getSimNumber() {
        return this.simNumber;
    }

    public void setSimNumber(String simNumber) {
        this.simNumber = simNumber;
    }

    public String getInitialPasscode() {
        return this.initialPasscode;
    }

    public void setInitialPasscode(String initialPasscode) {
        this.initialPasscode = initialPasscode;
    }

    public String getBikeId() {
        return this.bikeId;
    }

    public void setBikeId(String bikeId) {
        this.bikeId = bikeId;
    }

    public int getCapacity() {
        return this.capacity;
    }

    public void setCapacity(int capacity) {
        this.capacity = capacity;
    }

    public int getAvailable() {
        return this.available;
    }

    public void setAvailable(int available) {
        this.available = available;
    }

    public int getDeviceColor() {
        return this.deviceColor;
    }

    public void setDeviceColor(int deviceColor) {
        this.deviceColor = deviceColor;
    }

    public int getDeviceMode() {
        return this.deviceMode;
    }

    public void setDeviceMode(int deviceMode) {
        this.deviceMode = deviceMode;
    }

    public int getDeviceFwVersion() {
        return this.deviceFwVersion;
    }

    public void setDeviceFwVersion(int deviceFwVersion) {
        this.deviceFwVersion = deviceFwVersion;
    }

    public int getServerFwVersion() {
        return this.serverFwVersion;
    }

    public void setServerFwVersion(int serverFwVersion) {
        this.serverFwVersion = serverFwVersion;
    }

    public String getServerFwDisplayVersion() {
        return this.serverFwDisplayVersion;
    }

    public void setServerFwDisplayVersion(String serverFwDisplayVersion) {
        this.serverFwDisplayVersion = serverFwDisplayVersion;
    }

    public String getServerFwName() {
        return this.serverFwName;
    }

    public void setServerFwName(String serverFwName) {
        this.serverFwName = serverFwName;
    }

    public String getServerFwDate() {
        return this.serverFwDate;
    }

    public void setServerFwDate(String serverFwDate) {
        this.serverFwDate = serverFwDate;
    }

    public String getServerFwDesc() {
        return this.serverFwDesc;
    }

    public void setServerFwDesc(String serverFwDesc) {
        this.serverFwDesc = serverFwDesc;
    }

    public String getServerFwUpdateLog() {
        return this.serverFwUpdateLog;
    }

    public void setServerFwUpdateLog(String serverFwUpdateLog) {
        this.serverFwUpdateLog = serverFwUpdateLog;
    }

    public String getServerFwUrl() {
        return this.serverFwUrl;
    }

    public void setServerFwUrl(String serverFwUrl) {
        this.serverFwUrl = serverFwUrl;
    }

    public String getLocalFwFileName() {
        return this.localFwFileName;
    }

    public void setLocalFwFileName(String localFwFileName) {
        this.localFwFileName = localFwFileName;
    }

    public String getLocalFwFilePath() {
        return XZDeviceHelper.getFirmwarePath(this.type);
    }

    public void setLocalFwFilePath(String localFwFilePath) {
        this.localFwFilePath = localFwFilePath;
    }

    public String getDeviceFwDisplayVersion() {
        return this.deviceFwDisplayVersion;
    }

    public void setDeviceFwDisplayVersion(String deviceFwDisplayVersion) {
        this.deviceFwDisplayVersion = deviceFwDisplayVersion;
    }

    public int getDeviceAutoPower() {
        return this.deviceAutoPower;
    }

    public void setDeviceAutoPower(int deviceAutoPower) {
        this.deviceAutoPower = deviceAutoPower;
    }

    public int getDeviceWidthLight() {
        return this.deviceWidthLight;
    }

    public void setDeviceWidthLight(int deviceWidthLight) {
        this.deviceWidthLight = deviceWidthLight;
    }

    public int getDeviceTotalWheels() {
        return this.deviceTotalWheels;
    }

    public void setDeviceTotalWheels(int deviceTotalWheels) {
        this.deviceTotalWheels = deviceTotalWheels;
    }

    public int getDeviceTotalCranks() {
        return this.deviceTotalCranks;
    }

    public void setDeviceTotalCranks(int deviceTotalCranks) {
        this.deviceTotalCranks = deviceTotalCranks;
    }

    @Override
    public int getFlags() {
//        Log.d(TAG, "getFlags flags=" + this.flags + ", id="+this.getId());
        return this.flags;
    }

    @Override
    public void setFlags(int flags) {
//        Log.d(TAG, "setFlags flags=" + this.flags + ", id="+this.getId());
        this.flags = flags;
    }

    @Override
    public int getProtocol() {
        return this.protocol;
    }

    @Override
    public void setProtocol(int protocol) {
        this.protocol = protocol;
    }

    @Override
    public byte[] getScanRecord() {
        return this.scanRecord;
    }

    @Override
    public void setScanRecord(byte[] scanRecord) {
        this.scanRecord = scanRecord;
    }

    public boolean isNeedUpgrade() {
        if (DeviceContext.getDeviceConfiguration().isDfuDebuggable()) {
            return true;
        }
        if (findById(Device.class, this.id) == null) {
            return false;
        }
        String version = XZDeviceHelper.getVersion(this.type);
        String firmwarePath = XZDeviceHelper.getFirmwarePath(this.type);
        String str = this.deviceFwName;
        boolean z = str != null && !str.equals(version);
        File file = firmwarePath != null ? new File(firmwarePath) : null;
        return z && file != null && file.exists();
    }

    public static void storeOrReplaceDevice(int deviceType, String address, String name, int rssi,
                                            byte[] scanRecord, int protocol, boolean isInfoUpload) {
        Device device = new Device();
        device.setType(deviceType);
        device.setName(name);
        device.setAddress(address);
        device.setRssi(rssi);
        device.setScanRecord(scanRecord);
        device.setProtocol(protocol);
        device.setIsInfoUpload(isInfoUpload);
        storeDevice(device);
    }

    public static void storeOrReplaceDevice(int deviceType, String address, String name, int rssi,
                                            byte[] scanRecord, int protocol, boolean isInfoUpload, long userId) {
        Device byAddress = getByAddress(address);
        if (byAddress == null) {
            byAddress = new Device();
        }
        byAddress.setType(deviceType);
        byAddress.setName(name);
        byAddress.setAddress(address);
        byAddress.setRssi(rssi);
        byAddress.setScanRecord(scanRecord);
        byAddress.setProtocol(protocol);
        byAddress.setIsInfoUpload(isInfoUpload);
        byAddress.setUserId(userId);
//        Log.d(TAG, "storeOrReplaceDevice userId=" + userId);
        storeDevice(byAddress);
    }

    public String getDeviceFwName() {
        return this.deviceFwName;
    }

    public void setDeviceFwName(String deviceFwName) {
        this.deviceFwName = deviceFwName;
    }

    @Override
    public void writeToParcel(Parcel parcel, int i) {
        parcel.writeString(this.name);
        parcel.writeString(this.address);
        parcel.writeInt(this.type);
        parcel.writeInt(this.rssi);
        parcel.writeLong(this.userId);
        parcel.writeString(this.deviceUUID);
        parcel.writeInt(this.deviceNumber);
        parcel.writeString(this.simNumber);
        parcel.writeString(this.initialPasscode);
        parcel.writeString(this.bikeId);
        parcel.writeInt(this.capacity);
        parcel.writeInt(this.available);
        parcel.writeInt(this.deviceColor);
        parcel.writeInt(this.deviceMode);
        parcel.writeInt(this.deviceAutoPower);
        parcel.writeInt(this.deviceWidthLight);
        parcel.writeInt(this.deviceTotalWheels);
        parcel.writeInt(this.deviceTotalCranks);
        parcel.writeInt(this.deviceFwVersion);
        parcel.writeString(this.deviceFwDisplayVersion);
        parcel.writeInt(this.serverFwVersion);
        parcel.writeString(this.serverFwDisplayVersion);
        parcel.writeString(this.serverFwName);
        parcel.writeString(this.serverFwDate);
        parcel.writeString(this.serverFwDesc);
        parcel.writeString(this.serverFwUpdateLog);
        parcel.writeString(this.serverFwUrl);
        parcel.writeString(this.localFwFileName);
        parcel.writeString(this.localFwFilePath);
        parcel.writeByte(this.isInfoUpload ? (byte) 1 : (byte) 0);
        parcel.writeString(this.deviceFwName);
//        Log.d(TAG, "writeToParcel flags=" + this.flags);
        parcel.writeInt(this.flags);
        parcel.writeInt(this.protocol);
    }

    public static int[] getTypeSensorTypes() {
        return new int[]{TYPE_HR_X2_PRO, TYPE_CADENCE, TYPE_VORTEX_CADENCE, TYPE_HEARTRATE,
                TYPE_HEARTRATE_BELT, TYPE_RADAR_SR, TYPE_Q1, TYPE_LIGHT,TYPE_POWERRATE,
                TYPE_BIKE_TRAINER,TYPE_INDOOR_BIKE,TYPE_CROSS_TRAINER,TYPE_ROWER, TYPE_CADENCE01, TYPE_HEART_RATE01};
    }

    public static int[] getTypeCadenceAndSpeedTypes() {
        return new int[]{TYPE_CADENCE, TYPE_VORTEX_CADENCE, TYPE_Q1, TYPE_CADENCE01};
    }

    public static int[] getTypeCadenceOrSpeedTypes() {
        return new int[]{TYPE_CADENCE, TYPE_VORTEX_CADENCE, TYPE_Q1, TYPE_CADENCE01};
    }

    public static int[] getTypeHeartRateTypes() {
        return new int[]{TYPE_HEARTRATE, TYPE_HEARTRATE_BELT, TYPE_HR_X2_PRO, TYPE_HEART_RATE01};
    }

    public static int[] getTypePowerRateTypes() {
        return new int[]{TYPE_POWERRATE};
    }

    public static int[] getTypeBikeTrainerTypes() {
        return new int[]{ TYPE_BIKE_TRAINER};
    }

    public static int[] getTypeIndoorBikeTypes() {
        return new int[]{TYPE_INDOOR_BIKE};
    }

    public static int[] getTypeCrossTrainerTypes() {
        return new int[]{TYPE_CROSS_TRAINER};
    }

    public static int[] getTypeRowerTypes() {
        return new int[]{TYPE_ROWER};
    }
    public static boolean hasThisTypeDeviceBound(int vDeviceType) {
        boolean vRet;
        if (vDeviceType == TYPE_SENSORS) {
            vRet = !getDevicesByMultipleType(getTypeSensorTypes()).isEmpty();
        } else if (vDeviceType == TYPE_SENSOR_CADENCE_OR_SPEED) {
            vRet = !getDevicesByMultipleType(getTypeCadenceOrSpeedTypes()).isEmpty();
        } else if (vDeviceType == TYPE_SENSOR_CADENCE_AND_SPEED) {
            vRet = !getDevicesByMultipleType(getTypeCadenceAndSpeedTypes()).isEmpty();
        } else if (vDeviceType == TYPE_SENSOR_HEART_RATE) {
            vRet = !getDevicesByMultipleType(getTypeHeartRateTypes()).isEmpty();
        } else {
            vRet = getByType(vDeviceType) != null;
        }
        return vRet;
    }

    public static List<Device> getDevicesByMultipleType(int... vDeviceTypes) {
        ArrayList<Device> arrayList = new ArrayList<>();
        if (vDeviceTypes.length >= 2) {
            StringBuilder sb = new StringBuilder("type IN (");
            for (int i = 0; i < vDeviceTypes.length; i++) {
                sb.append(vDeviceTypes[i]);
                if (i != vDeviceTypes.length - 1) {
                    sb.append(",");
                }
            }
            sb.append(Separators.RPAREN);
            if (App.getContext().getSigninUser() == null || App.getContext().getSigninUser().getUid() <= 0) {
                return arrayList;
            }
            sb.append(" AND userId = ?");
            String userId = String.valueOf(App.getContext().getSigninUser().getUid());
			return LitePal.where(sb.toString(), userId).find(Device.class);
        }
        return getDevicesByLogicType(vDeviceTypes[0]);
    }

    public static List<Device> getDevicesByLogicType(int vDeviceType) {
        if (vDeviceType == TYPE_BIKE_COMPUTER) {
            return getDevicesByMultipleType(getBikeComputerTypes());
        }
        if (vDeviceType == TYPE_SENSORS) {
            return getDevicesByMultipleType(getTypeSensorTypes());
        }
        if (vDeviceType == TYPE_SENSOR_CADENCE_AND_SPEED) {
            return getDevicesByMultipleType(getTypeCadenceAndSpeedTypes());
        }
        if (vDeviceType == TYPE_SENSOR_CADENCE_OR_SPEED) {
            return getDevicesByMultipleType(getTypeCadenceOrSpeedTypes());
        }

        if (vDeviceType == TYPE_SENSOR_HEART_RATE) {
            return getDevicesByMultipleType(getTypeHeartRateTypes());
        }
        if (vDeviceType == TYPE_POWERRATE) {
            return getDevicesByMultipleType(getTypePowerRateTypes());
        }
        if (vDeviceType == TYPE_INDOOR_BIKE) {
            return getDevicesByMultipleType(getTypeIndoorBikeTypes());
        }
        if (vDeviceType == TYPE_CROSS_TRAINER) {
            return getDevicesByMultipleType(getTypeCrossTrainerTypes());
        }
        if (vDeviceType == TYPE_ROWER) {
            return getDevicesByMultipleType(getTypeRowerTypes());
        }

        if (vDeviceType == TYPE_BIKE_TRAINER) {
            return getDevicesByMultipleType(getTypeBikeTrainerTypes());
        } else {
            String devType = String.valueOf(vDeviceType);
            String userId = String.valueOf(App.getContext().getUserId());

            List<Device> l = LitePal.where(" type = ? and userId = ?", devType, userId).find(Device.class);
            return l;
        }
//        return i == 19 ? getDevicesByMultipleType(getTypeHeartRateTypes()) : Select.from(Device.class).where(" type = ? and user_id = ?", new String[]{String.valueOf(i), String.valueOf(App.getContext().getUserId())}).list();
    }

    public static boolean isThisTypeNeedAutoConnect(int targetType) {
        for (int i : getNeedAutoConnectTypes()) {
            if (targetType == i) {
                return true;
            }
        }
        return false;
    }

    public static boolean isSensorType(int targetType) {
        for (int i : getTypeSensorTypes()) {
            if (targetType == i) {
                return true;
            }
        }
        return false;
    }

    public static int[] getNeedAutoConnectTypes() {
        return new int[]{TYPE_CADENCE, TYPE_HEARTRATE, TYPE_HEARTRATE_BELT, TYPE_RADAR_SR,
                TYPE_VORTEX_CADENCE, TYPE_XOSS_G, TYPE_XOSS_NAV, TYPE_WINGS, TYPE_DISCOVERY,
                TYPE_Q1, TYPE_CHILEAF_600, TYPE_CYCLE_PLUS_M1, TYPE_CYCLE_PLUS_M2, TYPE_LIGHT,
                TYPE_HR_X2_PRO,TYPE_POWERRATE,TYPE_BIKE_TRAINER,TYPE_INDOOR_BIKE,
                TYPE_CROSS_TRAINER,TYPE_ROWER, TYPE_CADENCE01, TYPE_HEART_RATE01};//, TYPE_BES
    }

    public static int[] getBikeComputerTypes() {
        return new int[]{TYPE_BES, TYPE_XOSS_G, TYPE_XOSS_NAV, TYPE_WINGS, TYPE_DISCOVERY,
                TYPE_CHILEAF_600, TYPE_CYCLE_PLUS_M1, TYPE_CYCLE_PLUS_M2};
    }
}
